package TankFrst;
/*
子弹的信息
 */
import TankFrst.Missile;
import TankFrst.Msg;
import TankFrst.TankClient;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

public class MissileNewMsg implements Msg {
    int msgType=Msg.MISSILE_NEW_MSG;//子弹传输的消息

    TankClient tc;
    Missile m;

    public MissileNewMsg(TankClient tc) {
        this.tc = tc;
    }

    public MissileNewMsg(Missile m) {
        this.m = m;
    }

    @Override
    public void send(DatagramSocket ds, String IP, int udpPort) {
        //利用send方法来发送信息
        ByteArrayOutputStream baos = new ByteArrayOutputStream();//转换为字节输出
        DataOutputStream dos = new DataOutputStream(baos);
        try {
            /*
            将数据打包
            id,tank的横坐标和纵坐标，方向，坦克的好坏
             */
            dos.writeInt(msgType);//tank的类型
            dos.writeInt(m.tankId);//tank的id
            dos.writeInt(m.id);//子弹的id
            dos.writeInt(m.x);//子弹的横坐标
            dos.writeInt(m.y);//子弹的纵坐标
            dos.writeInt(m.dir.ordinal());//在枚举类型的下标值，即方向
            dos.writeBoolean(m.good);//子弹的好坏
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] buf = baos.toByteArray();//转换为字节数组
        DatagramPacket dp = new DatagramPacket(buf, buf.length, new InetSocketAddress(IP, udpPort));//将字节数组转换为Data包发送
        try {
            ds.send(dp);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void parse(DataInputStream dis) {
        try {
            int tankId=dis.readInt();//读入id号
            // 如果是自己的tank就返回
            if (tankId==tc.myTank.id) {
                return;
            }
            int id=dis.readInt();
            int x= dis.readInt();
            int y=dis.readInt();
            Dir dir=Dir.values()[dis.readInt()];//将方向的下标转换并且存储
            boolean good=dis.readBoolean();
//判断坦克是否存在
            Missile m=new Missile(tankId,x,y,good,dir,tc);
            m.id=id;
            tc.missiles.add(m);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
